package uhttp

import (
	"fmt"
	"os"
	"crypto/tls"
	"mime/multipart"
	"net/http"
	"bytes"
	"cloud_worm/util/ufile"
	"io"
)

func PostFile(filename string, targetUrl string) (*http.Response, error) {
	bodyBuf := bytes.NewBufferString("")
	bodyWriter := multipart.NewWriter(bodyBuf)

	// Add the other fields
	fw, err := bodyWriter.CreateFormField("md5")
	if err != nil {
		return nil, fmt.Errorf("create md5 error: %s", err.Error())
	}
	//计算md5
	md5 := ufile.GetFileMd5(filename)
	if md5 == "" {
		return nil, fmt.Errorf("get file md5 error: %s", err.Error())
	}
	// 写入md5的值
	_, err = fw.Write([]byte(md5))
	if err != nil {
		return nil, fmt.Errorf("write md5 error: %s", err.Error())
	}

	_, err = bodyWriter.CreateFormFile("file", filename)
	if err != nil {
		return nil, fmt.Errorf("create form file error: %s", err.Error())
	}

	fp, err := os.Open(filename)
	if err != nil {
		return nil, fmt.Errorf("open file error: %s", err.Error())
	}
	defer fp.Close()

	boundary := bodyWriter.Boundary()
	closeBuf := bytes.NewBufferString(fmt.Sprintf("\r\n--%s--\r\n", boundary))

	reqReader := io.MultiReader(bodyBuf, fp, closeBuf)

	fInfo, err := fp.Stat()
	if err != nil {
		return nil, fmt.Errorf("file stat error: %s", err.Error())
	}

	req, err := http.NewRequest("POST", targetUrl, reqReader)
	if err != nil {
		return nil, fmt.Errorf("new request error: %s", err.Error())
	}
	req.Header.Add("Content-Type", "multipart/form-data;boundary="+boundary)
	req.ContentLength = fInfo.Size() + int64(bodyBuf.Len()) + int64(closeBuf.Len())

	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true },
	}
	client := &http.Client{Transport: tr}

	return client.Do(req)
}
